/*
 * @copyright: Huang Ding
 * @Author: ding-cx
 * @Date: 2021-02-21 08:39:50
 * @LastEditors: ding-cx
 * @LastEditTime: 2021-03-27 09:33:44
 * @Description: file content
 */
import { Controller } from "egg";
// import {FuncController as Controller} from "../../../libs/controller/Common"
import * as captchapng from "captchapng";
import DateFormat from "@diyaner/dy-utils/libs/DateFormat";

import {Sequelize} from "sequelize"

export default class Captcha extends Controller {
  /**
   *生成验证码图片
   *
   * @memberof Captcha
   */
  async generate() {
    // await this.seq()
    this.ctx.body = await this.outputStrem();
  }

  // 数据库可通过参数动态去连接和关闭。但这样做很麻烦。orm预制的model无法使用。
  async seq(){
    const query = this.ctx.query;
    const seq = new Sequelize({
      dialect:'mysql',
      database:query.db,
      username:'root',
      password:"derlo123",
      host:"localhost",
      port:3309,
    })
    try {
      await seq.authenticate();
      console.log("连接成功！@");
      console.log(await seq.query("select * from sys_user"));
    } catch (error) {
      console.log("连接失败");
      console.log(error);
    }
    await seq.close()
  }



  /**
   *输出验证码图片
   *
   * @return {Stream} base64 的png验证码图片流
   * @memberof CaptchaService
   */
  private async outputStrem() {
    const { ctx } = this;
    // ctx.body += "service";
    // const word = "abcd";

    const word = parseInt((Math.random() * 9000 + 1000).toString());
    var p = new captchapng(80, 30, word); // width,height,numeric captcha
    p.color(255, 255, 255, 255); // First color: background (red, green, blue, alpha)
    p.color(80, 80, 80, 255); // Second color: paint (red, green, blue, alpha)

    const isSave = await this.saveIndexStr(word.toString());
    if (!isSave) return;
    var img = p.getBase64();
    var imgbase64 = Buffer.from(img, "base64");
    ctx.res.writeHead(200, {
      "Content-Type": "image/png",
    });

    return imgbase64;
  }

  /**
   *保存uuid，作为此验证码保存信息的唯一匹配凭证
   *
   * @memberof CaptchaService
   */
  private async saveIndexStr(word: string) {
    const row = {
      captcha_time: new DateFormat().format("yyyy-MM-dd hh:mm:ss"),
      cap_uuid: this.ctx.params.uuid,
      word,
      ip_address: this.ctx.request.ip,
    };
    // console.log(row);
    try {
      await this.app.model.Sys.Captcha.create(row);
      return true;
    } catch (error) {
      return false;
    }
  }
}
